package com.gl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gl.exception.BusinessException;
import com.gl.mapper.MeetingMapper;
import com.gl.mapper.UserMapper;
import com.gl.pojo.dto.MeetingPageDto;
import com.gl.pojo.entity.Meeting;
import com.gl.pojo.vo.AdminMeetingPageVo;
import com.gl.pojo.vo.MeetingCountVo;
import com.gl.pojo.vo.MeetingPageVo;
import com.gl.pojo.vo.MeetingVo;
import com.gl.service.MeetingService;
import com.gl.utils.CurrentHolder;
import com.gl.utils.UuidUtils;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.RedisVectorStore;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MeetingServiceImpl implements MeetingService {

    @Autowired
    private MeetingMapper meetingMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VectorStore vectorStore;

    // 创建会议
    @Override
    public String createMeeting(Meeting meeting) {
        String userId = CurrentHolder.getCurrentId();
        if (userId == null) {
            throw new BusinessException("用户不存在");
        }
        if (meeting.getStartTime() == null || meeting.getStartTime().isEmpty()) {
            meeting.setStartTime(String.valueOf(LocalDateTime.now()));
        }
        if (meeting.getTitle() == null || meeting.getTitle().isEmpty()) {
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义格式化为"X月Y日"的格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
            // 格式化日期
            String formattedDate = currentDate.format(formatter);
            meeting.setTitle(formattedDate + "会议");
        }
        String meetingId = UuidUtils.getUuid();
        meeting.setId(meetingId);
        meeting.setUserId(userId);

        try {
            int result = meetingMapper.insertMeeting(meeting);
            return result > 0 ? meetingId : null;
        } catch (Exception e) {
            throw new BusinessException("会议插入失败！");
        }
    }

    @Override
    public int updateMeeting(Meeting meeting) {
        if (meeting.getId() != null) {
            return meetingMapper.updateMeeting(meeting);
        }
        return 0;
    }

    @Override
    public Meeting getMeetingInfo(String meetingId) {
        if (meetingId == null) {
            return null;
        }
        return meetingMapper.selectById(meetingId);
    }

    /**
     * 保存会议录制
     *
     * @param meetingId 会议ID
     * @param recording 总结文本
     * @return -
     */
    @Override
    public int saveRecording(String meetingId, String recording) {
        if (meetingId != null && recording != null) {
            Meeting meeting = new Meeting();
            meeting.setId(meetingId);
            meeting.setRecording(recording);
            return meetingMapper.updateMeeting(meeting);
        }
        return 0;
    }

    @Override
    public int saveAISummary(String meetingId, String content) {
        if (meetingId != null && content != null) {
            Meeting meeting = new Meeting();
            meeting.setId(meetingId);
            meeting.setContent(content);
            return meetingMapper.updateMeeting(meeting);
        }
        return 0;
    }

    /**
     * 分页查询会议
     *
     * @param meetingPageDto 会议页信息
     * @return -
     */
    @Override
    public MeetingPageVo page(MeetingPageDto meetingPageDto) {
        if (meetingPageDto == null) meetingPageDto = new MeetingPageDto();
        meetingPageDto.setUserId(CurrentHolder.getCurrentId());
        Integer page = meetingPageDto.getPage();
        Integer pageSize = meetingPageDto.getPageSize();
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;

        PageHelper.startPage(page, pageSize);
        Page<Meeting> result = (Page<Meeting>) meetingMapper.pageQuery(meetingPageDto);
        //获取分页结果
        List<Meeting> meetingList = result.getResult();
        long total = result.getTotal();
        //封装
        MeetingPageVo meetingPageVo = new MeetingPageVo();
        meetingPageVo.setMeetingList(meetingList);
        meetingPageVo.setTotal(total);

        return meetingPageVo;
    }

    /**
     * 根据id删除会议
     *
     * @param meetingId 会议ID
     * @return -
     */
    @Override
    public int delete(String meetingId) {
        if (meetingId == null) {
            return 0;
        }
        return meetingMapper.deleteById(meetingId);
    }

    @Override
    public AdminMeetingPageVo pageAdmin(MeetingPageDto meetingPageDto) {
        if (meetingPageDto == null) meetingPageDto = new MeetingPageDto();
        Integer page = meetingPageDto.getPage();
        Integer pageSize = meetingPageDto.getPageSize();
        page = page == null ? 1 : page;
        pageSize = pageSize == null ? 10 : pageSize;

        PageHelper.startPage(page, pageSize);
        Page<MeetingVo> result = (Page<MeetingVo>) meetingMapper.adminPageQuery(meetingPageDto);
        //获取分页结果
        List<MeetingVo> meetingList = result.getResult();
        long total = result.getTotal();
        //封装
        AdminMeetingPageVo adminMeetingPageVo = new AdminMeetingPageVo();
        adminMeetingPageVo.setMeetingList(meetingList);
        adminMeetingPageVo.setTotal(total);

        return adminMeetingPageVo;
    }

    @Override
    public long countByUserId(String userId) {
        return meetingMapper.countByUserId(userId);
    }

    @Override
    public String getMeetingContent(String meetingId) {
        if (meetingId == null) {
            return null;
        }
        return meetingMapper.selectById(meetingId).getRecording();
    }


    @Autowired
    private RedisVectorStore redisVectorStore;

    @Override
    public String getMeetingMaterials(String meetingId, String query) {
        // todo yyl 修bug，bug：无法通过会议id过滤
        if (meetingId == null || query == null)return null;
        Filter.Expression filter = new FilterExpressionBuilder()
                .eq("meeting_id", meetingId)
                .build();
        // 执行相似性搜索
        List<Document> docs = vectorStore.similaritySearch(
                SearchRequest.query(query)
                        .withTopK(5) // 取最相关的5个文档块
                        .withFilterExpression(filter) // 过滤条件为会议id相同
        );

        // 拼接文档内容
        return docs.stream()
                .map(Document::getContent)
                .collect(Collectors.joining("\n\n---\n\n"));
    }

    /**
     * 根据时间范围统计会议数量
     *
     * @param start
     * @param end
     * @return
     */
    @Override
    public List<MeetingCountVo> countByTime(LocalDate start, LocalDate end) {
        if (start == null || end == null)return null;
        List<Meeting> meetings = meetingMapper.countByTime(start, end);
        // 使用Java Stream进行内存分组统计
        Map<LocalDate, Long> dailyCountMap = meetings.stream()
                .filter(meeting -> meeting.getStartTime() != null)
                .collect(Collectors.groupingBy(
                        meeting -> LocalDate.parse(meeting.getStartTime().split(" ")[0], DateTimeFormatter.ISO_DATE),
                        Collectors.counting()
                ));

        // 转换为VO对象
        return dailyCountMap.entrySet().stream()
                .map(entry -> new MeetingCountVo(entry.getKey(), entry.getValue().intValue()))
                .sorted(Comparator.comparing(MeetingCountVo::getDate))
                .collect(Collectors.toList());
    }
}
